package com.enjoy.server;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

public class SearchServer {

    static String APP_HOME = System.getProperty("APP_HOME");

    public static void initSolrHome(){
        System.setProperty("solr.solr.home",APP_HOME+"/solrCore");
    }


    public static void main(String[] args) throws Exception {


        initSolrHome();

        PropertiesLoaderUtils.fillProperties(System.getProperties(),
                new ClassPathResource("application.properties"));

        final int port = Integer.getInteger("jetty.port",8080);
        final Server server = new Server(port);
        WebAppContext context = new WebAppContext();
        context.setResourceBase(APP_HOME + "/webapp");
//        context.setDescriptor(usrDir+"/WEB-INF/web.xml");
        context.setContextPath("/");
        context.setParentLoaderPriority(true);

        server.setHandler(context);

        server.start();
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(" Stop Jetty Server On port : " + port);
                try {
                    server.stop();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }));
        server.join();
    }


    static {
        String PROJECT = "search";
        if( APP_HOME == null || APP_HOME.isEmpty()){
            String userDir = System.getProperty("user.dir");
            if(!userDir.endsWith(PROJECT)){
                userDir+="/"+PROJECT+"/";
            }
            APP_HOME = userDir +"/src/main";
        }
    }

}
